<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.jxgy_delete"
          @click="handleDelete"
          >删 除
        </el-button>
        <UploadStyle
          ref="uploadStyle"
          v-if="screenShotDialogVisible"
          :visible="screenShotDialogVisible"
          :img-url="imgUrl"
          :proportion="proportion"
          @closeDialog="closeDialog"
          @getImgURL="getImgURL"
        />
      </template>
      <template slot-scope="{ type, size, row, index }" slot="menu">
        <el-button
          type="text"
          size="small"
          @click="handleEditState({ type, size, row, index })"
          >修改状态</el-button
        >
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {
  getAiType,
  getAiList,
  eidtOraddlistAi,
  editAiStatus,
  deleteAi
} from "@/api/system/ai";
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      screenShotDialogVisible: false,
      imgUrl: "",
      backdone: null,
      proportion: [166, 108], // 宽高的像素数组
      backuploadLoading: null,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "auto",
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        menuType: "menu",
        menuBtnTitle: "更多操作",
        column: [
          // {
          //   label: "学校名称",
          //   prop: "schoolId",
          //   type: "tree",
          //   search: true,
          //   overHidden: true,
          //   cascader: ["xqId"],
          //   rules: [
          //     {
          //       required: true,
          //       message: "请选择学校",
          //       trigger: "blur",
          //     },
          //   ],
          //   dicUrl: "/api/ManageCourseSet/GetSchoolSelect",
          //   props: {
          //     label: "title",
          //     value: "id",
          //   },
          // },
          {
            label: "分类",
            prop: "typeId",
            overHidden: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请选择分类",
                trigger: "blur",
              },
            ],
            type: "select",
            dicData: [
              // {
              //   label: '教案助手',
              //   value: 1
              // },
              // {
              //   label: '知识点大纲',
              //   value: 2
              // },
              // {
              //   label: '活动策划',
              //   value: 3
              // },
            ],
            props: {
              label: 'dictValue',
              value: 'id'
            }
          },
          {
            label: "灵感标题",
            prop: "title",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入灵感标题",
                trigger: "blur",
              },
            ],
          },
          {
            label: "灵感描述",
            prop: "desc",
            type: 'textarea',
            rules: [
              {
                required: true,
                message: "请输入灵感描述",
                trigger: "blur",
              },
            ],
          },
          {
            label: "提示语",
            prop: "hint",
            type: 'textarea',
            hide: true,
            rules: [
              {
                required: true,
                message: "请输入提示语",
                trigger: "blur",
              },
            ],
          },
          {
            label: "提示示例",
            prop: "hintExamples",
            type: 'textarea',
            hide: true,
            rules: [
              {
                required: true,
                message: "请输入提示示例",
                trigger: "blur",
              },
            ],
            placeholder: "请输入提示实例,多个示例换行隔开",
          },
          {
            label: "AI message 模板",
            prop: "template",
            type: 'textarea',
            hide: true,
            rules: [
              {
                required: true,
                message: "请输入AI message 模板",
                trigger: "blur",
              },
            ],
          },
          {
            label: "封面图",
            prop: "pic",
            rules: [
              {
                required: true,
                message: "请上传封面图",
                trigger: "blur",
              },
            ],
            type: "upload",
            loadText: "封面图上传中，请稍等",
            // limit: 10,
            multiple: false,
            listType: 'picture-img',
            span: 24,
            accept: "image/*",
            propsHttp: {
              name: "name",
              url: "link",
              res: "data",
            },
            action: "/api/localfiles/uploadPcFile",
            tip: '只能上传jpg/png文件，且不超过500kb',
            hide: true,
            // viewDisplay: false,
            uploadBefore: (file, done, loading) => {
              this.screenShotDialogVisible = true
              const fileReader = new FileReader()
              fileReader.onload = (res) => {
                // 给图片裁切传递参数
                this.imgUrl = res.target.result
              }
              fileReader.readAsDataURL(file)
              // 备份
              this.backdone = done
              this.backuploadLoading = loading
              this.proportion = [166,108]
            }
          },
          {
            label: "是否启用",
            prop: "status",
            type: "switch",
            value: 0,
            dicData: [
              {
                label: "未启用",
                value: 0,
              },
              {
                label: "启用",
                value: 1,
              },
            ],
          },
        ],
      },
      data: [],
      fileIds: []
    };
  },
  computed: {
    ...mapGetters(["permission", "JSuserInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.jxgy_add, false),
        viewBtn: this.vaildData(this.permission.jxgy_view, false),
        delBtn: this.vaildData(this.permission.jxgy_delete, false),
        editBtn: this.vaildData(this.permission.jxgy_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  mounted() {
    this.getAiTypeData()
  },
  methods: {
    getAiTypeData() {
      getAiType({code: 'AIAFFLATUS'}).then(res => {
        const aiTypeData = res && res.data.data
        const aiType = this.findObject(this.option.column, "typeId");
        aiType.dicData = aiTypeData
      })
    },
    rowSave(row, done, loading) {
      row.id = row.id === "" ? "0" : row.id;
      eidtOraddlistAi(row).then(
        () => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      eidtOraddlistAi(row).then(
        () => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteAi({ ids: row.id });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteAi({ ids: this.ids });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done) {
      // if (["edit", "view"].includes(type)) {

      // }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.fileIds = []
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getAiList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    // 修改状态
    handleEditState({ row }) {
      this.$confirm("确定修改启用状态?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          editAiStatus({ id: row.id }).then((res) => {
            if (res.data.code == 200) {
              this.$message({type: 'success', message: res.data.msg || "操作成功"})
            }
          }).then(() => {
            this.query = {}
            this.onLoad(this.page);
          })
        })
    },

    closeDialog(val) {
      if (this.backuploadLoading !== null) {
        this.backuploadLoading();
        this.backuploadLoading = null;
      }
      this.screenShotDialogVisible = val;
    },
    getImgURL(data) {
      if (this.backdone !== null) {
        this.backdone(data);
        this.backdone = null;
      }
      this.closeDialog(false);
    },
  },
};
</script>

<style>
</style>
